/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.security.service.impl;

import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.common.constant.RedisConstant;
import com.chengcang.common.constant.TokenExpireConstant;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.redis.RedisUtils;
import com.chengcang.common.service.impl.BaseServiceImpl;
import com.chengcang.common.utils.TokenGenerator;
import com.chengcang.admin.modules.security.dao.SysUserTokenDao;
import com.chengcang.admin.modules.security.entity.SysUserTokenEntity;
import com.chengcang.admin.modules.security.service.SysUserTokenService;
import com.chengcang.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {


    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Result createToken(Long userId, Long tenantId) {
        //用户token
        String token;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + TokenExpireConstant.EXPIRE * 1000);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId);
        if (tokenEntity == null) {
            //生成一个token
            token = TokenGenerator.generateValue();

            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);
            tokenEntity.setTenantId(tenantId);

            //保存token
            this.insert(tokenEntity);
        } else {
            //判断token是否过期
            if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = TokenGenerator.generateValue();
            } else {
                token = tokenEntity.getToken();
            }

            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);
            tokenEntity.setTenantId(tenantId);

            //更新token
            this.updateById(tokenEntity);
        }

        Map<String, Object> map = new HashMap<>(2);
        map.put(Constant.TOKEN_HEADER, token);
        map.put("expire", TokenExpireConstant.EXPIRE);
        return new Result().ok(map);
    }

    @Override
    public void logout(Long userId) {

        clearCache(userId);
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        baseDao.updateToken(userId, token);
    }

    @Override
    public void clearCache(List<Long> userIds) {
        for (Long userId : userIds) {
            clearCache(userId);
        }
    }
    @Override
    public void clearCache(Long... userIds) {
        //清空redis用户信息
        for (Long userId : userIds) {
            SysUserTokenEntity sysUserTokenEntity = baseDao.getByUserId(userId);
            if (Objects.nonNull(sysUserTokenEntity)) {
                redisUtils.delete(sysUserTokenEntity.getToken());
                Optional.ofNullable(SecurityUser.getTenantId()).ifPresent(o -> {
                    String userKey = RedisConstant.SYS_USER + SecurityUser.getUserId();
                    redisUtils.delete(userKey);
                });
            }
        }
    }
}